package nat;


import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author: Miyako
 * @Date: 2024-07-18-18:00
 * @Description:
 */
public class ChartClient {
    private Socket socket;
    private Scanner sc = new Scanner(System.in);
    private String name;
    ChartClient(){
        try{
            System.out.println("Client Linking ...");
            socket = new Socket("127.0.0.1",8788);
            System.out.println("Client Link Success！");
        }catch (IOException e){
            System.out.println("Client Link deft");
        }
    }
    public void start() {
        String msg;
        try (PrintWriter pw = new PrintWriter(socket.getOutputStream(), true)) {
            new Thread(new ServerHandeler()).start();//创建一个新的线程用于接收
            System.out.println("输入你的昵称");
            name = sc.nextLine();
            pw.println(name+"加入聊天室捏");
            while (true) {
                System.out.println("键入信息>");
                msg = sc.nextLine();
                if ("exit".equalsIgnoreCase(msg)) {
                    break;
                }
                pw.println(name+":"+msg);
            }
            }
         catch(IOException e){
                System.out.println("Send Message deft");
            }
        }

       private class ServerHandeler implements Runnable{//客户端接收数据任务
           BufferedReader bw=null;
            @Override
            public void run() {
                try {
                    bw = new BufferedReader(
                            new InputStreamReader(
                                    socket.getInputStream()));
                    String str;
                    while ((str=bw.readLine())!=null){
                        if (!str.startsWith(name))//过滤器抛弃自己的数据
                        System.out.println(str);
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

    public static void main(String[] args) {
        new ChartClient().start();
    }
}
